package com.bigknow.appstore.common.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * 用于服务管理的加密解密类
 * Created by chaos on 2016/5/30.
 */
public class ResourceSecUtil {

    private final static String KEY = "resourceSecureRandom_1";

    /**
     * 加密
     *
     * @param content  需要加密的内容
     * @return
     */
    public final static String encrypt(String content) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(KEY.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secretKey.getEncoded(), "AES"));// 初始化
            return bytesToHexString(cipher.doFinal(content.getBytes("utf-8")));//加密
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }




    /**解密
     * @param content  待解密内容
     * @return
     */
    public final static String decrypt(String content) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(KEY.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(secretKey.getEncoded(), "AES"));// 初始化
            return new String(cipher.doFinal(hexStringToBytes(content))); // 加密
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }


    private static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}
